package ghostbanlistd;

import java.nio.ByteBuffer;

public class Ban {
	public static int BAN_CUSTOM = 0;
	public static int BAN_SPAM = 1; //spam joins, leaves, or whatever
	public static int BAN_EXPLOIT = 2;
	public static int BAN_KNOWNPROXY = 3;
	
	byte[] address; //4-byte IPv4 address, big endian
	int reasonCode; //one of the BAN_ fields
	String reasonString;
	long entryTime; //currentTimeMillis() when ban was added
	int database_id; //ID in the database; 0 if database doesn't use ID or -1 if not in database
	int apiID; //first four bytes of API key who added it
	
	public Ban(byte[] address, int reasonCode, String reasonString, int apiID) {
		this(address, reasonCode, reasonString, apiID, System.currentTimeMillis());
	}

	public Ban(byte[] address, int reasonCode, String reasonString, int apiID, long entryTime) {
		this(address, reasonCode, reasonString, apiID, entryTime, -1);
	}
	
	public Ban(byte[] address, int reasonCode, String reasonString, int apiID, long entryTime, int database_id) {
		this.address = address;
		this.reasonCode = reasonCode;
		this.reasonString = reasonString;
		this.entryTime = entryTime;
		this.database_id = database_id;
		this.apiID = apiID;
	}
	
	public boolean appendBytes(ByteBuffer buf) {
		if(buf.remaining() >= 4) {
			buf.put(address);
			return true;
		}
		
		return false;
	}
	
	//convert from IPv4 string representation (x.x.x.x) to bytes
	//returns null on failure
	public static byte[] getAddressBytes(String addressString) {
		String[] parts = addressString.split("\\.");
		
		if(parts.length == 4) {
			byte[] bytes = new byte[4];
			
			for(int i = 0; i < 4; i++) {
				try {
					bytes[i] = (byte) Integer.parseInt(parts[i]);
				} catch(NumberFormatException e) {
					return null;
				}
			}
			
			return bytes;
		} else {
			return null;
		}
	}
}
